package com.dddpeter.app.service;

import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.crypto.SecretKeyFactory;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.stereotype.Service;

import com.dddpeter.app.common.BusException;
import com.dddpeter.app.common.DESCoder;
import com.dddpeter.app.common.Md5Util;
import com.dddpeter.app.entity.User;
import com.dddpeter.app.object.BussinessService;

/**
 * @ClassName: LoginService
 * @Description: 登录服务实现类
 * @author Peter Lee
 * @date 2014年8月11日 下午2:11:18
 * 
 */
@Service
public class LoginService implements BussinessService {
	private static final Logger LOG = Logger.getLogger(LoginService.class);
	User user;
	String msg;
	Boolean login;
	
	Map<Object, Object> result = new HashMap<Object, Object>();
	@Resource
	HibernateTransactionManager txm;
	@Override
	public void init() {
      //初始化服务使用的方法，服务开始时调用
	}
	@Override
	public void service(String serviceName, Map<Object, Object> paramMap) {
		init();
		LOG.info("开始服务：" + serviceName);
		user = (User) paramMap.get("user");
		login = login(user);
		try {
		byte[] tmppass="".getBytes("UTF-8");
		Key key = DESCoder.initSecretKey(DESCoder.getSeed());
		tmppass=DESCoder.encrypt((user.getPassword())
						.getBytes("UTF-8"),key);
			
		user.setPassword(tmppass.toString());
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error(e.getLocalizedMessage());
		} catch (BusException e) {
			LOG.error(e.getMessage());
		}
		result.put("user", user);
		result.put("login", login);
		result.put("emsg", msg);
	}

	@Override
	public Map<Object, Object> output() {
		return result;
	}

	public boolean login(User user) {
		Query query = txm
				.getSessionFactory()
				.getCurrentSession()
				.createQuery(
						" select u from User as u where u.userName=:username and u.password=:passwd");
		query.setString("username", user.getUserName());
		query.setString("passwd", Md5Util.getMd5(user.getPassword()));
		List<Object> list = query.list();
		LOG.info("获得用户实体个数：" + list.size());
		Iterator<Object> it = list.iterator();
		User ur=null;
		while (it.hasNext()) {
			ur = (User) it.next();
			break;
		}
		if(ur!=null){
			msg = "欢迎用户[" + user.getUserName() + "]登录系统";
			user=ur;
			return true;
		}
		else{
			msg = "登录失败请检查用户名或者密码";
			return false;
		}
		

	}
}
